#include <iostream>
#include <pthread.h>
#include <vector>
#include <cstdio>
#include <unistd.h>
#include "lockguard.hpp"
using namespace std;

#define NUM 4

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

class threadData
{
public:
    threadData(int number)
    {
        threadname = "thread-" + to_string(number);
        // lock = mutex;
    }

public:
    string threadname;
    // pthread_mutex_t *lock;
};

int tickets = 1000; // 用多线程，模拟一轮抢票

// void *getTicket(void *args)
// {
//     threadData *td = static_cast<threadData*>(args);
//     const char *name = td->threadname.c_str();
//     while(true)
//     {
//         // 线程对于锁的竞争能力可能会不同
//         pthread_mutex_lock(&lock);   // 申请锁成功，才能往后执行，不成功，阻塞等待。
//         if(tickets > 0)
//         {
//             usleep(1000);
//             printf("who=%s, get a ticket: %d\n", name, tickets);
//             tickets--;
//             pthread_mutex_unlock(&lock);
//         }
//         else
//         {
//             pthread_mutex_unlock(&lock);
//             break;
//         }
//         usleep(13); // 用休眠来模拟抢到票的后续动作
//     }
//     printf("%s ... quit\n", name);

//     return nullptr;
// }

void *getTicket(void *args)
{
    threadData *td = static_cast<threadData *>(args);
    const char *name = td->threadname.c_str();
    while (true)
    {
        {
            LockGuard lockguard(&lock); // 临时的LockGuard对象，自动释放，RAII风格的锁
            if (tickets > 0)
            {
                usleep(1000);
                printf("who=%s, get a ticket: %d\n", name, tickets);
                tickets--;
            }
            else
                break;
        } // 这个花括号的目的是分隔开sleep，标识临界区
        usleep(13); // 用休眠来模拟抢到票的后续动作
    }
    printf("%s ... quit\n", name);

    return nullptr;
}

int main()
{
    // pthread_mutex_t lock;
    // pthread_mutex_init(&lock, nullptr);

    vector<pthread_t> tids;
    vector<threadData *> thread_datas;
    for (int i = 1; i <= NUM; i++)
    {
        pthread_t tid;
        threadData *td = new threadData(i);
        thread_datas.push_back(td);
        pthread_create(&tid, nullptr, getTicket, thread_datas[i - 1]);
        tids.push_back(tid);
    }

    for (auto thread : tids)
    {
        pthread_join(thread, nullptr);
    }

    for (auto td : thread_datas)
    {
        delete td;
    }

    // pthread_mutex_destroy(&lock);
    return 0;
}